package com.cuitrip.app;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.app.init.AppInitManager;
import com.cuitrip.app.init.InitializerListener;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.service.R;
import com.cuitrip.util.I118Util;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import com.lab.app.BaseActivity;
import com.lab.logtrack.AppLog;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.DisplayUtil;
import com.umeng.message.PushAgent;
import com.umeng.onlineconfig.OnlineConfigAgent;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created on 7/13.
 */
public class LogoActivity extends BaseActivity implements Handler.Callback {

    private static final int DURATION = 1500;
    private static final int GO_MAIN = 100;
    private static final int INIT = 101;
    @Bind(R.id.logo_img)
    ImageView logoImage;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ct_activity_logo);
        ButterKnife.bind(this);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setHotfix();
    }

    private void setHotfix() {
        runPushTag();
        OnlineConfigAgent.getInstance().setDebugMode(true);
        OnlineConfigAgent.getInstance().updateOnlineConfig(this);
        String hotFixValue = OnlineConfigAgent.getInstance().getConfigParams(this, "hotfix_open");
        if (!TextUtils.isEmpty(hotFixValue)) {
            try {
                JSONObject jsonObject = JSON.parseObject(hotFixValue);
                List<String> versionList = JSON.parseArray(jsonObject.get("version").toString(), String.class);
                if (versionList.contains(MainApplication.getInstance().getVersionName())) {
                    Dexter.checkPermission(new PermissionListener() {
                        @Override
                        public void onPermissionGranted(PermissionGrantedResponse response) {
                            AppInitManager.getInstance().initBugFix(AppCoreRuntime.context);
                            AppLog.e("BUG FIX");
                            gotoNext();
                        }

                        @Override
                        public void onPermissionDenied(PermissionDeniedResponse response) {
                            gotoNext();
                        }

                        @Override
                        public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {

                        }
                    }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    return;
                }
            } catch (Exception e) {

            }
        }
        gotoNext();
    }

    private void gotoNext() {
        Handler handler = new Handler(this);
        handler.sendMessage(handler.obtainMessage(INIT));
        handler.sendMessageDelayed(handler.obtainMessage(GO_MAIN), DURATION);
    }

    @Override
    protected void onResume() {
        super.onResume();
        animate();
    }

    private void animate() {
        logoImage.setAlpha(0.0f);
        int height = DisplayUtil.getDisplayHeight() / 6;
        logoImage.animate().alpha(1.0f).translationY(-height).setStartDelay(300).setDuration(1000).setInterpolator(new LinearInterpolator()).start();
    }

    private void gotoMain() {
        startActivity(new Intent(LogoActivity.this, IndexActivity.class));
        finish();
    }


    private void runPushTag() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    PushAgent.getInstance(AppCoreRuntime.context).getTagManager().reset();
                    PushAgent.getInstance(AppCoreRuntime.context).getTagManager().add("support:" + I118Util.getSupportLanguageTag());
                    PushAgent.getInstance(AppCoreRuntime.context).getTagManager().add("actual:" + I118Util.getH5LanguageTag());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }


    @Override
    public boolean handleMessage(Message message) {
        if (message.what == GO_MAIN) {
            if (AppInitManager.getInstance().isReadyToGo()) {
                gotoMain();
            } else {
                AppInitManager.getInstance().setInitializerListener(new InitializerListener() {
                    @Override
                    public void onFinished() {
                        gotoMain();
                    }
                });
            }
            return true;
        }
        if (message.what == INIT) {
            LoginInstance.getInstance(); //初始化用户信息
            CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();

            UserBusiness.updateDeviceToken(new ApiProxy(new IProxyCallback() {
                @Override
                public boolean onProxyResult(ProxyResult<?> result) {
                    return true;
                }
            }), userInfo);

            return true;
        }
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppInitManager.getInstance().removeInitializerListener();
    }
}
